<?php

/**
 * urCronHTMLCleanerToolkit.
 * Provide tools to clean HTML
 * 
 * @package  urCronPlugin
 * @author   Marc Weistroff <marc.weistroff@gmail.com>
 * @version: $Id: urCronHTMLCleanerToolkit.class.php 8 2009-06-09 17:06:22Z flambeur $
 * 
 */
class urCronHTMLCleanerToolkit
{
	static protected $instance;
	protected $_config = null;
	protected $_purifier = null;
	protected $_content = null;
	protected $_lexer = null;
	
	/**
   * Return the singleton of urCron
   * @return class urCron
   */
  static function getInstance()
  {
    if(!self::$instance instanceof urCronHTMLCleanerToolkit)
    {
      self::createInstance();
    }
    return self::$instance;
  }

  /**
   * Create the singleton of urCron
   */
  static function createInstance()
  {
  	self::$instance = new urCronHTMLCleanerToolkit();
		urCronPluginConfiguration::registerHTMLPurifier();
		$this->instance->configure();
  }
	
	/**
	 * @todo Would be great to load the config from a YAML file
	 */
	protected function configure()
	{
		$this->_config = HTMLPurifier_Config::createDefault();
    $this->_config->set('HTML', 'DefinitionID', 'google shared');
    $this->_config->set('HTML', 'DefinitionRev', 1);
    $this->_config->set('Filter', 'YouTube', true);
    $this->_config->set('HTML', 'ForbiddenAttributes', "img@style");
    $this->_config->set('HTML', 'ForbiddenElements', 'center, div');
    $this->_config->set('URI', 'HostBlacklist', 'feedburner.com');
		
		$this->_purifier = new HTMLPurifier($this->_config);
		$this->_context = new HTMLPurifier_Context();
    $this->_lexer = new HTMLPurifier_Lexer_DirectLex();
	}
	
	public function purify($content)
	{
		return $this->_purifier->purify($content);
	}
	
	public function shorten($content, $nbParagraph = 3)
	{
		$tokens = $lexer->tokenizeHTML($content, $this->_config, $this->_context);

    $cc = "";
    $pCount = 0;
		foreach($tokens as $token)
    {
      if($token instanceof HTMLPurifier_Token_Start)
      {
        $cc .= '<'.$token->name;
        foreach($token->attr as $k => $v)
				{
          $cc .= ' '.$k.'='.'"'.$v.'"';
				}
        $cc .= ">";
      }
      else if($token instanceof HTMLPurifier_Token_End)
      {
        $cc .= '</'.$token->name.'>';
        if($token->name == "p")
          $pCount++;
      }
      else if($token instanceof HTMLPurifier_Token_Text)
      {
        $cc .= $token->data;
      }
      else if($token instanceof HTMLPurifier_Token_Empty)
      {
        $cc .= "<".$token->name;
        foreach( $token->attr as $k => $v )
        {
          $cc .= ' '.$k.'='.'"'.$v.'"';
        }
        $cc .= ' />';
      }
      
      if($pCount == $nbParagraph)
        break;
    }
	}
		  
}

?>